package tiandang.core.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

@PropertySource("classpath:/pay.yml")
@ConfigurationProperties(prefix = "wechat.pay")
@Component
public class AESUtil {

  private static String mchKey;

  @Value("${mchKey}")
  public void setMchKey(String mchKey) {
    AESUtil.mchKey = mchKey;
  }

  /**
   * 密钥算法
   */
  private static final String ALGORITHM = "AES";
  /**
   * 加解密算法/工作模式/填充方式
   */
  private static final String ALGORITHM_MODE_PADDING = "AES/ECB/PKCS5Padding";

  /**
   * AES加密
   *
   * @param data
   * @return
   * @throws Exception
   */
  public static String encryptData(String data) throws Exception {
    // 创建密码器
    Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING);
    // 初始化
    SecretKeySpec key = new SecretKeySpec(MD5Util.MD5Encode(mchKey, "UTF-8").toLowerCase().getBytes(), ALGORITHM);
    cipher.init(Cipher.ENCRYPT_MODE, key);
    return Base64Util.encode(cipher.doFinal(data.getBytes()));
  }

  /**
   * AES解密
   *
   * @param base64Data
   * @return
   * @throws Exception
   */
  public static String decryptData(String base64Data) throws Exception {
    Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING);
    SecretKeySpec key = new SecretKeySpec(MD5Util.MD5Encode(mchKey, "UTF-8").toLowerCase().getBytes(), ALGORITHM);
    cipher.init(Cipher.DECRYPT_MODE, key);
    return new String(cipher.doFinal(Base64Util.decode(base64Data)));
  }

}
